<template>
  <div class="main">
    <p class="main_text">商户商品列表</p>
    <!-- 搜索 -->
    <div class="g-search" style="padding-top: 0" ref="searchBox">
      <!-- 顶部按钮区域 -->
      <!-- 时间选择区域 -->
      <div class="search_box1">
        <div class="demo-date-picker">
          <div class="block">
            <span class="demonstration" @change="startTime">商品创建时间：</span>
            <el-date-picker
              v-model="searchValue.startAt"
              type="date"
              placeholder="开始时间"
              @change="startTime"
              :clearable="false"
              :default-time="defaultTime(0, 0, 0)" />

            <span class="demonstration" style="display: inline-block; font-size: 12px; color: #898989; margin: 20px"
              >至</span
            >
            <el-date-picker
              v-model="searchValue.endAt"
              type="date"
              placeholder="结束时间"
              @change="endTime"
              :clearable="false"
              :default-time="defaultTime1(23, 59, 59)" />
          </div>
        </div>
        &emsp;
        <!-- 信息区域 -->
        <div class="all_select">
          <!-- 商品名称 -->
          <div class="input_valye">
            <span class="demonstration">商品名称：</span>
            <input
              type="text"
              class="input"
              placeholder="请输入商品名称"
              v-model="searchValue.name"
              style="width: 180px"
              @keyup.enter="search" />
          </div>
          <!-- 商品条/编码 -->
          <div class="input_valye">
            <span class="demonstration">商品条/编码：</span>
            <input
              type="text"
              class="input"
              placeholder="请输入商品条码"
              v-model="searchValue.productSn"
              style="width: 180px"
              @keyup.enter="search" />
          </div>
          <!-- 商品分组 -->
          <div class="input_valye">
            <span class="demonstration">商品分类：</span>
            <el-tree-select
              v-model="searchValue.type"
              :data="sort"
              :props="{label: 'name', value: 'id'}"
              :render-after-expand="false"
              @change="search">
              <template #default="{data: {name}}">{{ name }}</template>
            </el-tree-select>
          </div>
          <!-- 店铺id -->
          <div class="input_valye">
            <span class="demonstration">店铺ID:</span>
            <input
              type="text"
              class="input"
              placeholder="请输入店铺ID"
              v-model="searchValue.shopId"
              style="width: 180px"
              @keyup.enter="search" />
          </div>
          <!-- 店铺id -->
          <div class="input_valye">
            <span class="demonstration">公司名:</span>
            <input
              type="text"
              class="input"
              placeholder="请输入公司名"
              v-model="searchValue.companyName"
              style="width: 180px"
              @keyup.enter="search" />
          </div>
        </div>
      </div>
      <!-- 底部按钮区域 -->
      <div class="bottom_btn">
        <el-button class="solid" @click="search">查询</el-button>
        <el-button class="hollow" @click="reset">重置</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <div class="table cyr-flex">
      <!-- 表格导航栏 -->
      <div class="nav">
        <ul class="nav_ul">
          <li v-for="(item, index) in nav_list" :key="index" :class="item.class" @click="navChange(item)">
            <span class="nav_lis">{{ item.text }}</span>
          </li>
        </ul>
      </div>
      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        @select-all="handleSelectionChange"
        @select="handleSelectionChange"
        :header-cell-style="{'text-align': 'center'}"
        :show-overflow-tooltip="true"
        v-adaptive
        border>
        <el-table-column type="selection" width="40" />
        <el-table-column prop="shopId" label="店铺ID" width="120" align="center" />
        <el-table-column prop="shopName" label="店铺名" width="120" align="center">
          <template #default="props">
            <el-text tag="span" style="cursor: pointer" @click="bindEditGoods(props.row)">{{
              props.row.shopName
            }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="productSn" label="商品条/编码" width="120" align="center" />
        <el-table-column prop="name" label="商品名" width="150">
          <template #default="props">
            <el-text tag="span" :truncated="true" style="cursor: pointer">{{ props.row.name }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="pics" label="商品图" width="100" align="center">
          <template #default="item">
            <div v-if="item.row.decoration">
              <div v-if="item.row.decoration.turnImgs[0]">
                <el-image
                  style="width: 60px; height: 60px"
                  :preview-src-list="item.row.decoration.turnImgs"
                  :src="item.row.decoration.turnImgs[0]"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-teleported="true"
                  :hide-on-click-modal="true"
                  fit="cover" />
              </div>
              <div v-else>
                <div v-if="item.row.pics.length != 0">
                  <el-image
                    style="width: 60px; height: 60px"
                    :preview-src-list="picsUrl(item.row)"
                    :src="item.row.pics[0].url"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-teleported="true"
                    :hide-on-click-modal="true"
                    fit="cover" />
                </div>
                <div v-else>
                  <img :src="''" style="width: 100px; height: 100px" />
                </div>
              </div>
            </div>
            <div v-else>
              <div v-if="item.row.pics.length != 0">
                <el-image
                  style="width: 60px; height: 60px"
                  :preview-src-list="picsUrl(item.row)"
                  :src="item.row.pics[0].url"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-teleported="true"
                  :hide-on-click-modal="true"
                  fit="cover" />
              </div>
              <div v-else>
                <img :src="''" style="width: 100px; height: 100px" />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="salePrice" label="售价" width="100" align="center" />
        <el-table-column prop="linePrice" label="划线价" width="100" align="center" />
        <el-table-column prop="typeName" label="分类" width="100" align="center" />
        <el-table-column prop="createdAt" label="创建时间" width="180" align="center" />
        <el-table-column prop="updatedAt" label="更新时间" width="180" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-text v-if="scope.row.status == 0" class="mx-1" type="success"> • 未上架</el-text>
            <el-text v-else-if="scope.row.status == 1" class="mx-1" type="primary"> • 已上架</el-text>
            <el-text v-else-if="scope.row.status == 2" class="mx-1" type="warning"> • 已下架</el-text>
            <el-text v-else-if="scope.row.status == 3" class="mx-1" type="warning"> • 售罄</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="库存" width="100" align="center" />
        <el-table-column label="操作" width="150" class="operation" :show-overflow-tooltip="false">
          <template #default="item">
            <div class="table_btn">
              <el-button size="small" class="none" @click="bindEditGoods(item.row)">查看</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <smartPager
        v-model:current-page="searchValue.page"
        v-model:page-size="searchValue.rows"
        :total="total"
        @change="pageChange" />
    </div>
    <!-- 查看订单 -->
    <el-drawer v-model="orderShow" class="order" style="position: absolute !important; z-index: 40 !important">
      <div class="title">
        <el-image
          style="width: 100px; height: 100px; flex-shrink: 0"
          :preview-src-list="GoodsformDate.headImg"
          :src="GoodsformDate.headImg[0]"
          :max-scale="7"
          :min-scale="0.2"
          :preview-teleported="true"
          :hide-on-click-modal="true"
          fit="cover" />
        <div class="goods_mes">
          <div class="name">{{ GoodsformDate.name }}</div>
          <div class="goods_id">商品编号:{{ GoodsformDate.productSn }}</div>
          <div class="goods_shop">所属店铺:{{ GoodsformDate.shopName }}</div>
        </div>
      </div>
      <div class="goods_content">
        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Edit-name.png" alt="" />
          <div class="box_title">商品名称:</div>
          <div class="box_content">{{ GoodsformDate.name }}</div>
        </div>
        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Frame43.png" alt="" />
          <div class="box_title">商品编号:</div>
          <div class="box_content">{{ GoodsformDate.productSn }}</div>
        </div>
        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Application.png" alt="" />
          <div class="box_title">所属店铺:</div>
          <div class="box_content">{{ GoodsformDate.shopName }}</div>
        </div>
        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Frame43.png" alt="" />
          <div class="box_title">店铺ID:</div>
          <div class="box_content">{{ GoodsformDate.shopId }}</div>
        </div>
        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Car.png" alt="" />
          <div class="box_title">车型:</div>
          <div class="box_content">{{ GoodsformDate.typeName }}</div>
        </div>
        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Frame46.png" alt="" />
          <div class="box_title">分类:</div>
          <div class="box_content">{{ GoodsformDate.typeName }}</div>
        </div>
        <!-- <div class="box">
                    <div class="box_title">单位:</div>
                    <div class="box_content">{{ GoodsformDate.unit }}</div>
                </div> -->
        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Frame36.png" alt="" />
          <div class="box_title">售价:</div>
          <div class="box_content">{{ GoodsformDate.salePrice }}</div>
        </div>

        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Pencil.png" alt="" />
          <div class="box_title">划线价:</div>
          <div class="box_content">{{ GoodsformDate.linePrice }}</div>
        </div>
        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Home-two.png" alt="" />
          <div class="box_title">库存:</div>
          <div class="box_content">{{ GoodsformDate.quantity }}</div>
        </div>

        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Copy-one.png" alt="" />
          <div class="box_title">商品详情描述:</div>
          <div class="box_content">{{ GoodsformDate.description }}</div>
        </div>
        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/Carousel.png" alt="" />
          <div class="box_title">商品轮播图:</div>
          <div class="box_content">
            <img v-for="(item, index) in GoodsformDate.turnImgs" :key="index" :src="item" class="box_img" />
          </div>
        </div>
        <div class="box">
          <img class="img_b" src="@/assets/images/shop/goods/image.png" alt="" />
          <div class="box_title">商品详情图:</div>
          <div class="box_content">
            <img v-for="(item, index) in GoodsformDate.detailImgs" :key="index" :src="item" class="box_img" />
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted, onBeforeUnmount} from 'vue';
import type {UploadUserFile} from 'element-plus';
import moment from 'moment';
import {RequestGoodSort, RequestSynthesizeProduct} from '@/api/path/index.js';
const orderShow = ref(false);
/**
 * 返回处理后的图片数组
 */
const picsUrl = (item: any) => {
  let pics = <any>[];
  item.pics.forEach((it: any, index: number) => {
    pics[index] = it.url;
  });
  return pics;
};
const defaultTime = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
const defaultTime1 = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
const status = ref('');
// 搜索参数
const searchValue = ref({
  shopId: '',
  shopName: '',
  companyName: '',
  name: '',
  productSn: '',
  type: '',
  status: '',
  startAt: '',
  endAt: '',
  page: 1,
  rows: 10,
});
/**
 * 点击重置
 */
const reset = () => {
  searchValue.value = {
    shopId: '',
    shopName: '',
    companyName: '',
    name: '',
    productSn: '',
    type: '',
    status: '',
    startAt: '',
    endAt: '',
    page: 1,
    rows: 10,
  };
  requestSynthesizeProduct();
};
/**
 * 搜索栏所有数据，事件
 */
const fileList = ref<UploadUserFile[]>([]); //图片数组

// 挂载
onMounted(() => {
  requestSynthesizeProduct();
  getsort();
  handleResize();
  window.addEventListener('resize', handleResize);
});
const searchBox = ref();
const tablelistHeight = ref();
const handleResize = () => {
  const searchBoxHeight = searchBox.value.clientHeight;
  tablelistHeight.value = 110 + searchBoxHeight + 'px';
  console.log('Search Box height11111111111111111111111111111:', searchBoxHeight);
};

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});
const sort = ref([]); //商品联级选择器
// 获取联级分类
const getsort = async () => {
  const a = await RequestGoodSort();
  sort.value = a.resultObj;
  console.log(a.resultObj);
};

/**
 * 表格相关数据，事件
 */
const tableData = ref<any>([]); // 表格列表
const total = ref(0); //表格总数

/**
 * 表格导航列表
 */
const nav_list = ref([
  {
    class: ['navlist', 'nav_li'],
    text: '全部',
    status: '',
    num: 0,
  },
  {
    class: ['nav_li'],
    text: '销售中',
    status: 1,
    num: 0,
  },
  {
    class: ['nav_li'],
    text: '已售罄',
    status: 3,
    num: 0,
  },
  {
    class: ['nav_li'],
    text: '已下架',
    status: 2,
    num: 0,
  },
]);
const shopName = ref('');
// 获取表格列表
const requestSynthesizeProduct = async () => {
  status.value = '';
  const a = await RequestSynthesizeProduct(searchValue.value);
  tableData.value = a.resultObj.products;
  total.value = a.resultObj.totalCount;
  shopName.value = a.resultObj.shopName;
  console.log('获取成功', tableData.value);
};
// 表格颜色区分
const tableRowClassName = ({row, rowIndex}: any) => {
  // const rowIndex = tableDataParent.value.findIndex(item => item.id === id)
  if (rowIndex % 2 !== 0 || row.selection === true) {
    if (row.selection === true) {
      return 'check_table';
    } else {
      return 'warning-row';
    }
  } else {
    return '';
  }
};
/**
 * 表格导航点击事件
 */
const navChange = (item: any) => {
  status.value = item.status;
  for (let i = 0; i < nav_list.value.length; i++) {
    const filteredClasses = nav_list.value[i].class.filter((className) => className !== 'navlist');
    nav_list.value[i].class = filteredClasses;
  }
  item.class.push('navlist');
  searchValue.value.status = item.status;
  searchValue.value.page = 1;
  requestSynthesizeProduct();
};
const producIds = ref<any>([]);
// 表格多选事件
const handleSelectionChange = (selection: any) => {
  for (let x = 0; x < tableData.value.length; x++) {
    tableData.value[x].selection = false;
  }
  for (let i = 0; i < selection.length; i++) {
    selection[i].selection = true;
  }
  producIds.value = selection;
  console.log('选择', producIds.value);
};

// 添加,编辑商品列表
const GoodsformDate = ref<any>({
  headImg: '',
  id: '',
  productSn: '',
  name: '', //商品名称
  shopName: '', //店铺名
  shopId: '', //店铺id
  typeName: '', //分类
  unit: '', //单位
  salePrice: '', //售价
  linePrice: '', //划线价
  quantity: '', //库存
  description: '', //商品描述
  turnImgs: [], //商品主图
  detailImgs: [], //商品详情图
});
// 点击编辑
const bindEditGoods = (item: any) => {
  console.log('查看', item);
  orderShow.value = true;
  GoodsformDate.value = {
    headImg: picsUrl(item),
    id: item.id, //商品id
    productSn: item.productSn, //商品编号
    name: item.name, //商品名称
    shopName: item.shopName, //店铺名
    shopId: item.shopId, //店铺id
    typeName: item.typeName, //分类名
    unit: item.unit, //单位
    standards: item.standards, //规格
    salePrice: item.salePrice, //售价
    linePrice: item.linePrice, //划线价
    quantity: item.quantity, //库存
    description: item.description, //商品描述
    mainImgUrl: item.decoration ? item.decoration.turnImgs : [], //商品主图
    detailImgs: item.decoration ? item.decoration.detailImgs : [], //商品详情图
  };
  console.log('zzzzzzzzzzzzzzzzzzzzzzzzzzz', item.decoration, Boolean(item.decoration));

  if (item.decoration) {
    if (item.decoration.turnImgs[0]) {
      GoodsformDate.value.headImg = item.decoration.turnImgs;
    }
  }
  console.log('编辑', GoodsformDate.value);
  fileList.value = item.pics;
};

// 开始时间
const startTime = () => {
  searchValue.value.startAt.setHours(0);
  searchValue.value.startAt.setMinutes(0);
  searchValue.value.startAt.setSeconds(0);
  searchValue.value.startAt = moment(searchValue.value.startAt).format('yyyy-MM-DD HH:mm:ss');
  search();
};
// 结束时间
const endTime = () => {
  searchValue.value.endAt.setHours(23);
  searchValue.value.endAt.setMinutes(59);
  searchValue.value.endAt.setSeconds(59);
  searchValue.value.endAt = moment(searchValue.value.endAt).format('yyyy-MM-DD HH:mm:ss');
  search();
};
const search = () => {
  console.log('搜索', searchValue.value);
  status.value = searchValue.value.status;
  if (moment(searchValue.value.startAt).diff(moment().format('YYYY-MM-DD HH:mm:ss')) >= 0) {
    ElMessage.error('开始时间不能晚于当前日期');
    searchValue.value.startAt = '';
  } else {
    // 判断是否两个时间都填写了
    if (searchValue.value.startAt !== '' && searchValue.value.endAt !== '') {
      // 判断开始时间不能晚于结束时间
      if (moment(searchValue.value.startAt).diff(moment(searchValue.value.endAt)) <= 0) {
        requestSynthesizeProduct();
      } else {
        ElMessage.error('结束时间不能早于开始时间');
        searchValue.value.endAt = '';
      }
    } else {
      // 表示两个时间填写了任意一个
      searchValue.value.page = 1;
      requestSynthesizeProduct();
    }
  }
};
/**
 * 分页
 */
const pageChange = async (val: number) => {
  requestSynthesizeProduct();
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/plateform/Article/Content.css';
@import '@/assets/css/plateform/Shop/GoodsManage.css';

.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.table {
  height: calc(100% - v-bind(tablelistHeight)) !important;
}

::v-deep .el-table--fit {
  height: calc(100% - 120px) !important;
}

.table :deep(.el-table__cell) {
  text-align: center;
}

.el-table {
  margin-top: 20px;
}

:deep(.el-drawer.rtl) {
  background: #f5f9ff;
  width: 500px !important;
}

.nav_ul {
  width: 100%;

  .nav_li {
    width: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .nav_lis {
    position: relative;
    cursor: pointer;

    .number {
      padding: 0 5px;
      display: block;
      line-height: 16px;
      height: 16px;
      color: #fff;
      font-size: 12px;
      background: #409eff;
      border-radius: 8px;
      position: absolute;
      top: 2px;
      right: -12px;
    }
  }

  .navlist {
    .number {
      background: #409eff;
      color: #fff;
    }
  }
}

.title {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #dfdfdf;

  .goods_mes {
    width: calc(100% - 120px);
    margin-left: 10px;
    overflow: hidden;

    .name {
      font-size: 16px;
      font-weight: bold;
      width: 100%;
      text-overflow: ellipsis;
      text-wrap: nowrap;
      overflow-x: hidden;
    }

    .goods_id {
      color: #b8b8b8;
      font-size: 12px;
    }

    .goods_shop {
      color: #b8b8b8;
      font-size: 12px;
    }
  }
}

.goods_content {
  .box {
    display: flex;
    margin-top: 20px;
    align-items: center;

    .img_b {
      width: 16px;
      height: 16px;
      margin-right: 5px;
    }

    .box_title {
      color: #8a8a8a;
      font-size: 14px;
      width: 160px;
    }

    .box_content {
      width: calc(100% - 200px);
      font-size: 14px;
      color: #050505;
      text-overflow: ellipsis;
      text-wrap: nowrap;
      overflow-x: hidden;
    }

    .box_img {
      width: 50px;
      height: 50px;
      margin-right: 10px;
    }
  }
}
</style>
